package com.xmb.wechat.view.wechat.chat;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Switch;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseViewHolder;
import com.squareup.picasso.Picasso;
import com.xmb.wechat.R;
import com.xmb.wechat.R2;
import com.xmb.wechat.application.WechatStartApplication;
import com.xmb.wechat.base.BaseActivity;
import com.xmb.wechat.bean.GroupTalkBean;
import com.xmb.wechat.bean.WechatContactBean;
import com.xmb.wechat.definterface.GroupTalkListener;
import com.xmb.wechat.definterface.OnEditRoleListener;
import com.xmb.wechat.definterface.PicChooseWithCutCallBack;
import com.xmb.wechat.definterface.SimpleTextWatcher;
import com.xmb.wechat.definterface.onBgChooseListener;
import com.xmb.wechat.delegate.GroupTalkAddDelegate;
import com.xmb.wechat.dialog.BGSelectDailog;
import com.xmb.wechat.dialog.RoleEditDialog;
import com.xmb.wechat.util.PicChooseUtils;
import com.xmb.wechat.util.PicLoadUtils;
import com.xmb.wechat.widget.TitleLayout;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.objectbox.relation.ToMany;

/**
 * @Author lijiangop
 * @CreateTime 2020/4/14 16:53
 */
public class WechatQunliaoAddActivity extends BaseActivity {

    private static final int REQUEST_CODE_IMAGE   = 101;
    private static final int REQUEST_CODE_EDIT    = 103;
    private static final int REQUEST_CODE_REPLACE = 104;

    @BindView(R2.id.title_layout)
    TitleLayout  mTitleLayout;
    @BindView(R2.id.recyclerView)
    RecyclerView mRecyclerView;
    @BindView(R2.id.et_name)
    EditText     mEtName;
    @BindView(R2.id.et_numbers)
    EditText     mEtNumbers;
    @BindView(R2.id.iv_bg)
    ImageView    mIvBg;
    @BindView(R2.id.switch_no_dis)
    Switch       mSwitchNoDis;
    @BindView(R2.id.switch_show)
    Switch       mSwitchShow;
    @BindView(R2.id.btn_add)
    Button       mBtnAdd;

    private GroupTalkBean        mGroupTalkBean;
    private BGSelectDailog       mBgSelectDialog;
    private RoleEditDialog       mRoleEditDialog;
    private GroupTalkAddDelegate mDelegate;
    private boolean              isAdd;
    private int                  mCurrentEditPosition;
    private ItemTouchHelper      mItemTouchHelper;

    public WechatQunliaoAddActivity() {
        super(R.layout.activity_wechat_qunliao_add);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        super.onCreate(savedInstanceState);
    }

    public static void start4Result(Activity activity, int requestCode) {
        Intent intent = new Intent(activity, WechatQunliaoAddActivity.class);
        activity.startActivityForResult(intent, requestCode);
    }

    public static void start4Result(Activity activity, GroupTalkBean groupTalkBean, int requestCode) {
        Intent intent = new Intent(activity, WechatQunliaoAddActivity.class);
        intent.putExtra("data", groupTalkBean);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    protected void initView() {
        //init
        mDelegate = new GroupTalkAddDelegate(this, new GroupTalkListener() {
            @Override
            public void onClick(int position, WechatContactBean item) {
                if (mRoleEditDialog == null) {
                    mRoleEditDialog = new RoleEditDialog(WechatQunliaoAddActivity.this, new OnEditRoleListener() {
                        @Override
                        public void onEdit(int indexOf, WechatContactBean editBean) {
                            mCurrentEditPosition = indexOf;
                            WechatContactAddActivity.start4Edit4Result(WechatQunliaoAddActivity.this, editBean, REQUEST_CODE_EDIT);
                        }

                        @Override
                        public void onReplace(int indexOf) {
                            mCurrentEditPosition = indexOf;
                            WechatContactsActivity.startForResult(WechatQunliaoAddActivity.this, true, REQUEST_CODE_REPLACE);
                        }

                        @Override
                        public void onRemove(int indexOf) {
                            mDelegate.removeItem(indexOf);
                        }
                    });
                }
                mRoleEditDialog.setCurrentPosition(position);
                mRoleEditDialog.setCurrentItem(item);
                mRoleEditDialog.show();
            }

            @Override
            public void onItemDrag(BaseViewHolder helper) {
                if (mItemTouchHelper != null)
                    mItemTouchHelper.startDrag(helper);
            }
        });
        //拖拽helper
        mItemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.Callback() {
            @Override
            public int getMovementFlags(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder) {
                final int dragFlags = ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT | ItemTouchHelper.UP | ItemTouchHelper.DOWN;
                final int swipeFlags = 0;
                return makeMovementFlags(dragFlags, swipeFlags);
            }

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                //得到当拖拽的viewHolder的Position
                int fromPosition = viewHolder.getAdapterPosition();
                //拿到当前拖拽到的item的viewHolder
                int toPosition = target.getAdapterPosition();
                if (fromPosition < toPosition) {
                    for (int i = fromPosition; i < toPosition; i++) {
                        Collections.swap(mDelegate.getData(), i, i + 1);
                    }
                } else {
                    for (int i = fromPosition; i > toPosition; i--) {
                        Collections.swap(mDelegate.getData(), i, i - 1);
                    }
                }
                mDelegate.getAdapter().notifyItemMoved(fromPosition, toPosition);
                return true;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
            }

            @Override
            public boolean isLongPressDragEnabled() {
                return false;
            }
        });
        mItemTouchHelper.attachToRecyclerView(mRecyclerView);

        //titleLayout
        mTitleLayout.setRightClick(v -> checkValueUsable());
        mEtName.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChangedFinish(String value) {
                if (mGroupTalkBean != null)
                    mGroupTalkBean.setGroupName(value);
            }
        });
        mEtNumbers.addTextChangedListener(new SimpleTextWatcher() {
            @Override
            public void onTextChangedFinish(String value) {
                try {
                    if (TextUtils.isEmpty(value))
                        return;
                    int i = Integer.parseInt(value);
                    if (i < 3) {
                        ToastUtils.showShort("最少3人");
                        mEtNumbers.setText("3");
                        i = 3;
                    }
                    if (mGroupTalkBean != null)
                        mGroupTalkBean.setGroupMembers(i);
                } catch (NumberFormatException ex) {
                    ex.printStackTrace();
                }
            }
        });
        mSwitchNoDis.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mGroupTalkBean != null)
                    mGroupTalkBean.setNoDisturbing(isChecked);
            }
        });
        mSwitchShow.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (mGroupTalkBean != null)
                    mGroupTalkBean.setShowNickName(isChecked);
            }
        });
        showView();
    }

    private void showView() {
        GroupTalkBean data = (GroupTalkBean) getIntent().getSerializableExtra("data");
        if (data == null) {//新增
            mGroupTalkBean = new GroupTalkBean();
            isAdd = true;
        } else {//编辑
            mGroupTalkBean = data;
            ToMany<WechatContactBean> groupMembersList = mGroupTalkBean.getGroupMembersList();
            //排序
            ArrayList<WechatContactBean> sourceData = new ArrayList<>(groupMembersList);
            Collections.sort(sourceData, new Comparator<WechatContactBean>() {
                @Override
                public int compare(WechatContactBean o1, WechatContactBean o2) {
                    return o1.getGroupSort() - o2.getGroupSort();
                }
            });
            mDelegate.addData(sourceData);
            mEtName.setText(TextUtils.isEmpty(mGroupTalkBean.getGroupName()) ? "" : mGroupTalkBean.getGroupName());
            mEtNumbers.setText(String.valueOf(mGroupTalkBean.getGroupMembers()));
            if (!TextUtils.isEmpty(mGroupTalkBean.getGroupBg()))
                PicLoadUtils.loadChatBg(mGroupTalkBean.getGroupBg(), mIvBg);
            mSwitchNoDis.setChecked(mGroupTalkBean.isNoDisturbing());
            mSwitchShow.setChecked(mGroupTalkBean.isShowNickName());
            mBtnAdd.setText("保存修改");
        }
    }

    @OnClick({R2.id.re_add, R2.id.ll_bg, R2.id.btn_add})
    public void onViewClicked(View view) {
        int id = view.getId();
        if (id == R.id.re_add) {
            showRoleChooseSender(this, false, false, null);
        } else if (id == R.id.ll_bg) {
            if (mBgSelectDialog == null) {
                mBgSelectDialog = new BGSelectDailog(WechatQunliaoAddActivity.this, new onBgChooseListener() {

                    @Override
                    public void onDefaultChoose() {
                        mGroupTalkBean.setGroupBg("default");
                        Picasso.get().load(R.drawable.img_default_gray).into(mIvBg);
                    }

                    @Override
                    public void onUserDefinedChoose() {
                        PicChooseUtils.chooseOnePicWithCut(WechatQunliaoAddActivity.this, new PicChooseWithCutCallBack() {
                            @Override
                            public void onPicChoose(String... Pic) {
                                if (TextUtils.isEmpty(Pic[0]))
                                    return;
                                PicLoadUtils.loadSdcardPic(Pic[0], mIvBg);
                                if (mGroupTalkBean != null)
                                    mGroupTalkBean.setGroupBg(Pic[0]);
                            }
                        });
                    }
                });
            }
            mBgSelectDialog.show();
        } else if (id == R.id.btn_add) {
            checkValueUsable();
        }
    }

    private void checkValueUsable() {
        if (mDelegate == null)
            return;
        if (mDelegate.getData().size() == 0) {
            ToastUtils.showShort("请添加成员");
            return;
        }
        if (mDelegate.getData().size() < 3) {
            ToastUtils.showShort("群聊成员最少添加3人");
            return;
        }
        if (TextUtils.isEmpty(mEtName.getText().toString().trim())) {
            ToastUtils.showShort("请填写群聊名称");
            return;
        }
        mGroupTalkBean.setGroupName(mEtName.getText().toString().trim());
        if (mGroupTalkBean == null)
            return;
        //获取群聊成员集合
        List<WechatContactBean> data = mDelegate.getData();
        int count = 0;
        //添加排序标记
        for (WechatContactBean wechatContactBean : data) {
            wechatContactBean.setGroupSort(count);
            count++;
        }
        mGroupTalkBean.getGroupMembersList().clear();
        mGroupTalkBean.getGroupMembersList().addAll(data);
        //存入数据库
        WechatStartApplication.getBoxStore(this).boxFor(WechatContactBean.class).put(data);//保存排序标志
        WechatStartApplication.getBoxStore(this).boxFor(GroupTalkBean.class).put(mGroupTalkBean);//保存群聊数据
        ToastUtils.showShort("保存成功！");
        //finish
        Intent intent = new Intent();
        if (isAdd)
            intent.putExtra("GroupTalkBean", mGroupTalkBean);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE_OTHER_SEND || requestCode == REQUEST_CODE_CHOOSE_NEW_ADD_SEND) {//选择成员
            if (data == null)
                return;
            WechatContactBean result = (WechatContactBean) data.getSerializableExtra("result");
            if (result == null)
                return;
            List<WechatContactBean> target = mDelegate.getData();
            if (target.contains(result)) {
                ToastUtils.showShort("已添加该联系人");
                return;
            }
            mDelegate.additem(result);
            mEtNumbers.setText(String.valueOf(Math.max(mDelegate.getData().size(), 3)));

        }  else if (requestCode == REQUEST_CODE_EDIT) {//编辑角色
            if (data == null)
                return;
            WechatContactBean result = (WechatContactBean) data.getSerializableExtra("result");
            if (result == null)
                return;
            if (mCurrentEditPosition < 0 || mCurrentEditPosition > mDelegate.getData().size() - 1)
                return;
            mDelegate.removeItem(mCurrentEditPosition);
            mDelegate.getData().add(mCurrentEditPosition, result);

        } else if (requestCode == REQUEST_CODE_REPLACE) {//替换角色
            if (data == null)
                return;
            WechatContactBean result = (WechatContactBean) data.getSerializableExtra("result");
            if (result == null)
                return;
            if (mDelegate.getData().contains(result)) {
                ToastUtils.showShort("已添加该联系人");
                return;
            }
            if (mCurrentEditPosition < 0 || mCurrentEditPosition > mDelegate.getData().size() - 1)
                return;
            mDelegate.removeItem(mCurrentEditPosition);
            mDelegate.getData().add(mCurrentEditPosition, result);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mBgSelectDialog != null) {
            mBgSelectDialog.dismiss();
            mBgSelectDialog = null;
        }
        if (mRoleEditDialog != null) {
            mRoleEditDialog.dismiss();
            mRoleEditDialog = null;
        }
    }
}
